package jmars.mobile.datainvestigation;

import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import jmars.mobile.common.Investigator;
import jmars.mobile.common.PropertiesLoader;

/**
 * 2012.11.16 20:01 Friday - 2012.11.23 04:59 Friday 17~22
 * 2012.10.26 23:00 Friday - 2012.10.28 01:59 Sunday 27
 * @author Jan
 *
 */
public class Summary {
	public static String inputDir=PropertiesLoader.getProperty("inputDir");
	public static String outputDir=PropertiesLoader.getProperty("outputDir");
	public static String outputSuffix=PropertiesLoader.getProperty("outputSuffix");
	public static String fileList=PropertiesLoader.getProperty("fileList");
	public static String summaryPlugin=PropertiesLoader.getProperty("summaryPlugin");
//	public static String filterRegExp=PropertiesLoader.getProperty("filterRegExp");
	public static String columnSeperator=PropertiesLoader.getProperty("columnSeperator");
	public static String dateFormat=PropertiesLoader.getProperty("dateFormat");
	public static String[] filenames;
	public static String[] columns;
	private static String groupColumnIndexes=PropertiesLoader.getProperty("groupColumnIndexes");
	private static String targetColumnIndexes=PropertiesLoader.getProperty("targetColumnIndexes");
	public static Integer[] groupColumnIdx;
	public static Integer[] targetColumnIdx;
	public static String outputFilename;
	public static String groupColumns="";
	public static String targetColumns="";
	public static Integer batch;
	public static String filterLac;
	public static String filterCI;
	public static boolean errorResume;
	public static int columnCount;
	private static SimpleDateFormat sdf;
	public static DecimalFormat intFormat = new DecimalFormat("0");
	public static DecimalFormat oneFloatFormat = new DecimalFormat("0.0");
	public static DecimalFormat twoFloatFormat = new DecimalFormat("0.00");
	public static DecimalFormat threeFloatFormat = new DecimalFormat("0.000");
	
	private static void configurate(){
		TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
		sdf = new SimpleDateFormat(Summary.dateFormat);
		columns=PropertiesLoader.getProperty("columns").split(columnSeperator);
		columnCount=columns.length;
//		if(null!=filterRegExp&&!"".equals(filterRegExp)){
//			if(filterRegExp.charAt(0)!='^')filterRegExp=".*"+filterRegExp;
//			if(filterRegExp.charAt(filterRegExp.length()-1)!='$')filterRegExp=filterRegExp+".*";
//		}
		if("".equals(fileList))filenames=null;
		else filenames=fileList.split(",");
		outputFilename = outputDir+File.separator+summaryPlugin;
		String[] tempIdx = groupColumnIndexes.split(",");
		groupColumnIdx = new Integer[tempIdx.length];
		if(targetColumnIndexes!=null&!"".equals(targetColumnIndexes)){
			String[] targetIdx = targetColumnIndexes.split(",");
			targetColumnIdx=new Integer[targetIdx.length];
			for(int i=0,l=targetIdx.length;i<l;i++){
				targetColumnIdx[i]=Integer.parseInt(targetIdx[i]);
			}
		}else{
			targetColumnIdx=new Integer[tempIdx.length];
		}
		for(int i=0,l=tempIdx.length;i<l;i++){
			if(tempIdx[i]==null||"".equals(tempIdx[i]))continue;
			groupColumnIdx[i]=Integer.parseInt(tempIdx[i]);
			outputFilename = outputFilename + "_" + columns[groupColumnIdx[i]];
			if(targetColumnIndexes==null||"".equals(targetColumnIndexes)){
				targetColumnIdx[i]=Integer.parseInt(tempIdx[i]);
			}
			groupColumns = groupColumns + columns[groupColumnIdx[i]];
			if(i<l-1) groupColumns = groupColumns + ", ";
		}
		for(int i=0,l=targetColumnIdx.length;i<l;i++){
			if(targetColumnIdx[i]==null)continue;
			if(targetColumnIndexes!=null&&!"".equals(targetColumnIndexes))
				outputFilename = outputFilename + "-" + columns[targetColumnIdx[i]];
			targetColumns = targetColumns + columns[targetColumnIdx[i]];
			if(i<l-1) targetColumns = targetColumns + ", ";
		}
		outputFilename = outputFilename +outputSuffix+ ".txt";
		if(PropertiesLoader.getProperty("batch")==null||"".equals(PropertiesLoader.getProperty("batch")))
			batch=null;
		else
			batch=Integer.parseInt(PropertiesLoader.getProperty("batch"));
		filterLac = (null==PropertiesLoader.getProperty("filter.lac")?null:(","+PropertiesLoader.getProperty("filter.lac")+","));
		filterCI = (null==PropertiesLoader.getProperty("filter.ci")?null:(","+PropertiesLoader.getProperty("filter.ci")+","));
		errorResume = ("1".equals(PropertiesLoader.getProperty("errorresume"))||"y".equalsIgnoreCase(PropertiesLoader.getProperty("errorresume"))||
				"t".equalsIgnoreCase(PropertiesLoader.getProperty("errorresume"))||"yes".equalsIgnoreCase(PropertiesLoader.getProperty("errorresume"))||
				"true".equalsIgnoreCase(PropertiesLoader.getProperty("errorresume")));
	}
	

	public static Date parseBeginDate(String[] cols){
		Date tempDate;
		try {
			tempDate = sdf.parse(cols[5]);
			//data cleaning, date range is from 2012-10-24 00:00:00 to 2012-11-26 00:00:00.
//			if(tempDate.getTime()<1351036800000L||tempDate.getTime()>1353888000000L) return null;
			
//			if(tempDate.getTime()<1351256399000L)return null;
//			if(tempDate.getTime()>1351342801000L&&tempDate.getTime()<1353070799000L)return null;
//			if(tempDate.getTime()>1353589201000L)return null;
		} catch (Exception e) {
			return null;
		}
		return tempDate;
	}
	
	public static boolean checkLACI(String[] cols){
		return ((filterLac==null||filterLac.equals(",,")||filterLac.indexOf(","+cols[1]+",")!=-1)&&(filterCI==null||filterCI.equals(",,")||filterCI.indexOf(","+cols[2]+",")!=-1));
	}

	//true to skip
	public static boolean filterRowExcludeLACI(String[] cols,boolean checkGroupIndex,boolean checkTargetIndex){
		if(checkGroupIndex&&Summary.groupColumnIdx!=null){
			for(Integer idx:Summary.groupColumnIdx){
				if(idx!=null&&cols.length-1<idx)return true;
			}
		}
		if(checkTargetIndex&&Summary.targetColumnIdx!=null){
			for(Integer idx:Summary.targetColumnIdx){
				if(idx!=null&&cols.length-1<idx)return true;
			}
		}
		return false;
	}
	
	//true to skip
	public static boolean filterRow(String[] cols,boolean checkGroupIndex,boolean checkTargetIndex){
		if(filterRowExcludeLACI(cols,checkGroupIndex,checkTargetIndex))return true;
		
		if(filterLac!=null&&!filterLac.equals(",,")&&filterLac.indexOf(","+cols[1]+",")==-1) return true;
		if(filterCI!=null&&!filterCI.equals(",,")&&filterCI.indexOf(","+cols[2]+",")==-1) return true;
		return false;
	}
	public static String formatColumn(String[] cols,int index){
		if(index==4)//format traffic type as major category
			return ("".equals(cols[index])?"":cols[index].substring(0,1));
		else
			return cols[index];
	}
	
	public static String genGroupKey(String[] cols){
		String groupKey="";
		for(Integer idx:Summary.groupColumnIdx){
			if(idx<cols.length) {
				groupKey=groupKey+"$_$"+cols[idx]+"$_$";
			}
			else groupKey=groupKey+"$_$$_$";
		}
		return groupKey;
	}
	
	public static String genTargetKey(String[] cols){
		String targetKey="";
		for(Integer idx:Summary.targetColumnIdx){
			if(idx<cols.length) {
				targetKey=targetKey+"$_$"+Summary.formatColumn(cols, idx)+"$_$";
			}
			else targetKey=targetKey+"$_$$_$";
		}
		return targetKey;
	}
	
//	public static boolean filterRow(String row){
//		return null!=Summary.filterRegExp&&!"".equals(Summary.filterRegExp)&&!row.matches(Summary.filterRegExp);
//	}

	public static void main(String[] args) throws Exception {
		configurate();
		Resource r= new FileSystemResource(inputDir);
		FilenameFilter fnf=new FilenameFilter(){
			@Override
			public boolean accept(File dir, String name) {
				if(filenames==null)return true;
				else for(String fn:filenames){
					if(fn.equals(name))return true;
				}
				return false;
			}
		};
		FileWriter resultWriter;
		File fDir = new File(outputDir);
		if(!fDir.exists())fDir.mkdirs();
		resultWriter = new FileWriter(outputFilename);
		Class<?> c = Class.forName(summaryPlugin);
		Investigator worker = (Investigator)c.newInstance();
		System.out.println(summaryPlugin+", group by ["+groupColumns+"] START.");
		List<File> tworkfiles=new ArrayList<File>();
		for(File f:r.getFile().listFiles(fnf)){
			if(!f.isDirectory())tworkfiles.add(f);
		}
		File[] workfiles = new File[tworkfiles.size()];
		int fidx=0;
		for(File f:tworkfiles){
			workfiles[fidx]=f;
			fidx++;
		}
		Object ro = worker.compute(workfiles, resultWriter);
		Long resultCount=null;
		if(ro!=null) resultCount = Long.parseLong(ro.toString());
		resultWriter.close();
		System.out.println("All done. "+resultCount);
	}

}
